const common = require('../../utils/commonUtil.js');
const {requestDetail,requestCommentList,doSign,commentAdd,wantToGO,getInitDetailState,commentLike,requestServer,URL_LIKE_COMMENT} = require('../../utils/netUtils.js');
const {doLogin,checkAndGetLocAuthorize} = require('../../utils/loginUtil');
const WxParse = require('../../wxParse/wxParse.js');

Page({
    onShareAppMessage(e) {
        console.log(e)
        return {
            //title: '想参加'+this.data.data.title+'，一起么？',
            title: this.data.data.title,
            path: 'pages/exhibit-detail/detail?id='+getApp().globalData.tempId
        }
    },
    data: {
        textAreaMaxLength:400,
        textAreaCurrLength:0,
        loading:true,
        noDataShow:false,
        videoShow:false,
        selfScore:0,
        isSignOk:false,
        commentList:[],
        commentTempList:[],
        init:{},
        commentPlaceholder:'活动满足你的期待吗？说说体会，分享给想参与的小伙伴吧~~',
        imagePrefix: common.imagePrefix
    },
    getValidSubStr: function (content) {
        let temp =content.substring(0,170);
        if(temp.length>5){
            for(let i=1;i<=8;i++){
                if(temp.charAt(temp.length-i)==='<'){//出现标签被截断的情况
                    temp =content.substring(0,170-i);
                    return temp;
                }
            }
        }
        return temp;
    },
    handleInterest:function(str){
        let tempArr = str.split(',');
        while (tempArr.join('/').length > 16) {
            tempArr.pop();
        }
        return tempArr.join('/');
    },
    onLoad: function (option) {
        let id = option.id;
        getApp().globalData.tempId=id;
        requestDetail({id},res=>{
            console.log({type:'详情接口返回',res});
            if(res.status==='200'){
                let timeStrObj = common.timeUtil.genStartEndTime(res.data.startTime,res.data.endTime);
                res.data.startTime = timeStrObj.start;
                res.data.endTime = timeStrObj.end;
                res.data.peoples=[...res.data.exhibitionZhanxunRelationDtos,...res.data.artistZhanxunRelationDtos];
                let interestArr = res.data.interest.split(',');
                if(interestArr.length>3){
                    res.data.interest = interestArr[0]+','+interestArr[1]+','+interestArr[2];
                }
                let categoryArr = res.data.firstCategory.split(',');
                if(categoryArr.length>3){
                    res.data.firstCategory = categoryArr[0]+','+categoryArr[1]+','+categoryArr[2];
                }

                res.data.score = Number(res.data.score).toFixed(1);
                res.data.interest = this.handleInterest(res.data.interest);


                res.data.stadiumInfo = common.recoverHtml(res.data.stadiumInfo||'');
                res.data.stadiumAddr = common.recoverHtml(res.data.stadiumAddr||'');


                //此处为详情展开与隐藏功能
                /*let contentTemp ='';
                let contentForParse = common.recoverHtml(res.data.content);
                if(contentForParse&&contentForParse.length>170){
                    contentTemp = this.getValidSubStr(contentForParse)+'...';
                }else if(contentForParse){
                    contentTemp = contentForParse+'   ';
                }
                this.setData({data:res.data,loading:false,contentTemp,contentForParse});
                WxParse.wxParse('article', 'html', contentTemp, this, 0);*/

                let contentTemp = common.recoverHtml(res.data.content);
                this.setData({data:res.data,loading:false,contentTemp});
                WxParse.wxParse('article', 'html', contentTemp, this, 0);


                let title = res.data.title;
                wx.setNavigationBarTitle({title});
                this.getCommentList(id);
                getInitDetailState({relationId:id},ret=>{
                    if(ret.status==='200'){
                        let selfScore = ret.data.score>0?ret.data.score:0;
                        this.setData({init:ret.data,selfScore,isSignOk:!!ret.data.isSign});
                    }
                })
            }else{
                this.setData({loading:false,noDataShow:true});
            }
        });
        let isSignOk = common.storage.getFromLocal('isSignOk'+id);
        if(isSignOk){
            this.setData({isSignOk});
        }
    },
    getCommentList:function(id){
        requestCommentList({relationId:id},ret=>{
            console.log({type:'评论接口返回',ret});
            if(ret.status==='200'){
                ret.data.dtoList.map(item=>{
                    item.updateTime = common.timeUtil.formatTime(item.updateTime,'Y.M.D');
                });
                this.setData({commentList:ret.data.dtoList,commentTempList:ret.data.dtoList.slice(0,5)});
            }
        });
    },

    showAllComment:function(){
        this.setData({commentTempList:this.data.commentList})
    },

    onReady: function () {
        checkAndGetLocAuthorize();
    },
    onShow: function () {
    },
    onHide: function () {
    },
    onUnload: function () {
    },
    onPullDownRefresh: function () {
        // Do something when pull down.
        wx.stopPullDownRefresh();
    },
    onReachBottom: function () {
    },
    onStarBarResult:function (e) {//打分结果回传
        let score = e.detail.score;
        console.log({score});
        if(score>0){
            this.setData({selfScore:score});
        }else{
            common.toast('请先签到后再打分','none');
        }
    },
    onSignClick(){//签到
        if(this.data.isSignOk){
            common.toast('您已经签到成功','none');
            return;
        }
        checkAndGetLocAuthorize(isOk=>{//授权成功后的回调
            if(isOk){
                doSign(getApp().globalData.tempId,ret=>{
                    if(ret.status==='200'){
                        common.toast('签到成功');
                        this.setData({isSignOk:true,'data.signinCount':ret.data,'init.isSign':1});
                    }else{
                        common.toast(ret.msg,'none');
                        if(ret.msg.indexOf('已签到')>0){
                            this.setData({isSignOk:true,'init.isSign':1});
                        }
                    }
                });
            }else{
                wx.showModal({
                    title: '怎样签到？',
                    content: '只有授权位置信息才能签到哦~~',
                    showCancel: false,
                    confirmText: '确定',
                    confirmColor:'#333',
                    success (res) {
                        if (res.confirm) {
                            wx.openSetting({
                                success (res) {
                                    console.log(res.authSetting)
                                }
                            })
                        } else if (res.cancel) {
                            console.log('用户位置授权点击取消')
                        }
                    }
                })
            }
        });
    },
    onHelpClick(){//打分帮助
        this.setData({dialogShow:true,showHelp:true});
    },
    onAddrDetailClick(){//查看地址详情
        this.setData({dialogShow:true})
    },

    closeDialog(){
        this.setData({dialogShow:false,showHelp:false,inputBarShow:false})
    },
    onGotUserInfo(res){//个人信息授权回调
        let handleType = res.currentTarget.dataset.type;
        let rest = res.currentTarget.dataset.rest;
        console.log({type:'个人信息授权回调',res});
        let unionid = common.storage.getFromLocal('unionid');
        if(unionid){
            this.handleByType(handleType,rest);
        }else{
            if(res.detail.errMsg.indexOf('ok')>-1){
                let userInfo = res.detail;
                if(userInfo){
                    doLogin(userInfo.encryptedData,userInfo.iv,()=>{
                        //登录完成再刷一下页面
                        let id = getApp().globalData.tempId;
                        getInitDetailState({relationId:id},ret=>{
                            if(ret.status==='200'){
                                let selfScore = ret.data.score>0?ret.data.score:0;
                                this.setData({init:ret.data,selfScore,isSignOk:!!ret.data.isSign});
                            }
                            //继续干登录之前打算干的事
                            this.handleByType(handleType);
                        });
                    });
                }
            }
        }
    },

    handleByType(handleType,rest){
        switch (handleType) {
            case 'say':
                this.showInputBar();
                break;
            case 'sign':
                this.onSignClick();
                break;
            case 'want':
                this.onWantGo();
                break;
            case 'like-comment':
                this.onGoodClick(rest);
                break;
        }
    },

    showInputBar(){
       this.setData({inputBarShow:true},()=>{
           let b=this.data.inputBarShow&&!this.data.init.comment;
           console.log({bar:this.data.inputBarShow,comment:!this.data.init.comment,b});
           
           this.setData({inputFocus:b});
       })
    },
    onWantGo(){
        let id=getApp().globalData.tempId;
        let nowExpect=!!this.data.init.isExpect;
        // console.log(nowExpect);
        wantToGO({id,status:nowExpect?0:1},ret=>{
            if(ret.status==='200'){
               /* this.data.data.expectCount=ret.data;
                this.setData({'data.expectCount':ret.data,'init.isExpect':nowExpect?0:1});*/
                if(nowExpect){
                    //不能取消不想去
                    return false
                }
                let count = this.data.data.expectCount;
                count = count+(nowExpect?-1:1);
                this.setData({'data.expectCount':count,'init.isExpect':nowExpect?0:1});
                // if(nowExpect){
                //     common.toast('已取消','none');
                // }
            }
        })
    },
    copyAddr(){
        wx.setClipboardData({
            data: this.data.data.stadiumAddr||'地址暂无',
            success(res) {
                wx.getClipboardData({
                    success(res) {
                       common.toast('复制成功');
                    }
                })
            }
        })
    },
    openMap(){
        wx.openLocation({
            longitude: Number(this.data.data.stadiumLongitude),
            latitude: Number(this.data.data.stadiumLatitude),
            /*longitude: Number(115.675392),
            latitude: Number(37.772072),*/
            name: this.data.stadiumName,
            address: this.data.stadiumAddr
        })
    },
    onCommentInput(e){
        let {value,cursor}=e.detail;
        this.setData({textAreaCurrLength:cursor,userInput:value});
    },

    pubComment(){
        //检查用户输入
        let comment = this.data.userInput;
        let score = this.data.selfScore;
        if(this.data.init.comment&&this.data.init.comment.comment){//如果用户之前提交过评论，则本次不能再提交
            comment = null;
            if(score>0){//只提交打分
                this.pubCommentAfterCheck(comment,score);
            }else{//否则拒绝本次操作
                common.toast('请完成打分后再发布','none');
            }
        }else if(comment&&comment.length>10){
            this.pubCommentAfterCheck(comment,score);
        }else{
            common.toast('请输入不少于10个字','none');
        }
    },

    pubCommentAfterCheck(comment,score){
        wx.showLoading({
            title: '发表中..',
            mask:false
        });
        let unionId = common.storage.getFromLocal('unionid');
        let id=getApp().globalData.tempId;
        let postData = {sourceId:id,relationId:id,score,unionId};
        if(comment){
            postData.comment = comment;
        }
        commentAdd(postData,ret=>{
            console.log(ret);
            wx.hideLoading();
            let scoreCount = this.data.data.scoreCount+(score>0?1:0);
            let data = {inputBarShow:false,'data.scoreCount':scoreCount};
            if(comment){
                comment = {comment};
                data['init.comment']=comment;
                this.pushCommentToList(comment.comment,score||0);
            }

            if(score){
                data['init.score']=score;
                let count = data['data.scoreCount']-1;
                count = count<0?0:count;
                let avScore = this.data.data.score||0;
                data['data.score'] = ((count*avScore+score)/(count+1)).toFixed(1);
                //this.selectComponent("#star-bar").setShowScore(data['data.score']);
            }

            this.setData(data,()=>{
                common.toast('发布成功','none');
            });
        })
    },

    pushCommentToList(comment,score){
        let userInfoStr = common.storage.getFromLocal('userInfo');
        if(userInfoStr){
            let userInfo = JSON.parse(userInfoStr);
            let temp={
                comment,
                headIcon:userInfo.avatarUrl,
                wechatIcon:userInfo.avatarUrl,
                ursName:userInfo.nickName,
                updateTime:common.timeUtil.formatTime(new Date().getTime(),'Y.M.D'),
                score:score
            };
            let tempList = this.data.commentTempList;
            let tempListAll = this.data.commentList;
            if(tempList.length>0&&tempList[0].ursName===temp.ursName){
                tempList[0]=temp;tempListAll[0]=temp;
            }else{
                tempList.unshift(temp);tempListAll.unshift(temp);
            }
            this.setData({commentTempList:tempList,commentList:tempListAll})
        }
    },

    onGoodClick(id){
        console.log("good commentId",id);
        /*requestServer(URL_LIKE_COMMENT+'/id',{},ret=>{
            console.log(ret);
            this.data.commentTempList.map(item=>{
                if(item.id===id){
                    item.likeNum = item.likeNum+1;
                    item.isLiked = true;
                    return item;
                }
            });
            this.setData({commentTempList:this.data.commentTempList});
        });*/
        commentLike({id},ret=>{
            console.log(ret);
            if(ret.status==='200'){
                this.data.commentTempList.map(item=>{
                    if(item.id===id){
                        item.likeNum = item.likeNum+1;
                        item.isLiked = true;
                        return item;
                    }
                });
                this.setData({commentTempList:this.data.commentTempList});
            }else{
                common.toast(ret.msg,'error');
            }
        });
    },


    showAllContent(){

        /*contentTemp.length===data.content.length}}>收起</view>
            {{contentTemp.length-3<data.content.length}}">展开</view>*/
        let content;
        if(this.data.contentTemp.length===this.data.contentForParse.length){//收起
            content = this.getValidSubStr(this.data.contentForParse)+'...';
        }else if(this.data.contentTemp.length-3<this.data.contentForParse.length){//展开
            content = this.data.contentForParse;
        }
        WxParse.wxParse('article', 'html', content, this, 0);
        setTimeout(()=>{
            this.setData({contentTemp:content});
        },0);
    },

    showVideo(){
        //this.setData({videoShow:true,videoSrc:this.data.data.zhanxunVideoDtoList[0]}||this.data.videoSrc);
    },
    closeVideo(){
        wx.createVideoContext('inner-video',this).stop();
        this.setData({videoShow:false,});
    },
    preventTouchMov(){    },
});
